package com.wangyf.thread2;

import java.util.concurrent.TimeUnit;

/**
 * 如何优雅的结束一个线程
 * @author wangyf
 * @date 2021/7/12 19:41
 */
public class T04_HowToStopThread {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            for(;;) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Thread is interrupted, break !");
                    break;
                } else {
                    System.out.println("Thread is not interrupted, running !");
                }
            }
        });

        t.start();

        TimeUnit.SECONDS.sleep(1);
        // 这里只是设置了中断标志位，结合线程的实现代码（比如代码中有break或return），从而结束了线程
        t.interrupt();
    }
}
